package com.qh.yyxt.service.Impl;

import com.qh.yyxt.entity.*;
import com.qh.yyxt.mapper.*;
import com.qh.yyxt.pojo.BorrowThingDTO;
import com.qh.yyxt.pojo.BorrowThingInfoDTO;
import com.qh.yyxt.pojo.TableDTO;
import com.qh.yyxt.pojo.entity.thing.Thing;
import com.qh.yyxt.pojo.entity.thing.ThingSize;
import com.qh.yyxt.pojo.entity.meeting.User;
import com.qh.yyxt.service.BorrowThingService;
import com.qh.yyxt.word.WordTemplate;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@Service
public class BorrowThingServiceImpl implements BorrowThingService {

    @Autowired
    private BorrowThingMapper borrowThingMapper;
    @Autowired
    private ThingMapper thingMapper;
    @Autowired
    private ThingSizeMapper thingSizeMapper;
    @Autowired
    private FlagMapper flagMapper;
    @Autowired
    private GetAndReturnMapper getAndReturnMapper;
    @Autowired
    private DelayThingMapper delayThingMapper;
    @Override
    public int newAddBorrowThing(Flag flag, int tId[], int sId[], int nums[]){
        int result=1;
        //把tid一样的num算出来
        Map<Integer,Integer> map=new LinkedHashMap<>();
        for(int i=0;i<tId.length;i++){
            if(map.containsKey(tId[i])){
                map.put(tId[i],map.get(tId[i])+nums[i]);
            }else{
                map.put(tId[i],nums[i]);
            }
        }

        //存数据 先存flag
        Date date=new Date();
        User user=(User) SecurityUtils.getSubject().getPrincipal();
        flag.setUid(user.getId());
        flag.setApplytime(date);
        flag.setState("待审批");
        flag.setExamineState("未借出");
        flagMapper.insert(flag);
//        result = flagMapper.addFlag(flag);

        int fid=flag.getId();
        System.out.println("fid："+fid);
        List<BorrowThing>list=new ArrayList<>();
        for(int i=0;i<tId.length;i++) {
            BorrowThing borrowThing=new BorrowThing();
            borrowThing.setTid(tId[i]);
            borrowThing.setSid(sId[i]);
            borrowThing.setFid(fid);
            borrowThing.setNum(nums[i]);
            borrowThing.setAcnum(nums[i]);
            borrowThing.setBadnum(0);
            borrowThing.setState("待审批");
            list.add(borrowThing);
        }
        result=borrowThingMapper.addBorrowThing(list);
        return result;

    }

    @Override
    public int addBorrowThing(Flag flag, int tId[], int sId[], int nums[])
    {
        int result=1;
        //把tid一样的num算出来

        Map<Integer,Integer> map=new LinkedHashMap<>();
        for(int i=0;i<tId.length;i++)
        {

            if(map.containsKey(tId[i]))
            {
                int n=map.get(tId[i]);
                map.put(tId[i],n+nums[i]);
            }else{
                map.put(tId[i],nums[i]);
            }
        }
        //判断由谁审批？
        String state="审批通过";
        for (Map.Entry entry : map.entrySet())
        {
            //System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
            Thing thing=thingMapper.findById((Integer) entry.getKey());

            if(thing.getApprove1()<(Integer) entry.getValue())
            {
                state="待审批";
                break;
            }
        }
        //存数据 先存flag
        Date date=new Date();
        User user=(User) SecurityUtils.getSubject().getPrincipal();
        flag.setUid(user.getId());
        flag.setApplytime(date);
        flag.setState(state);
        if(state.equals("审批通过"))
        {
            flag.setPasstime(date);
            flag.setApprover("自动审批");
        }
        result=flagMapper.addFlag(flag);
        if(result==0)
            return 0;
        int fid=flag.getId();
        List<BorrowThing>list=new ArrayList<>();
        for(int i=0;i<tId.length;i++)
        {
            BorrowThing borrowThing=new BorrowThing();
            borrowThing.setTid(tId[i]);
            borrowThing.setSid(sId[i]);
            borrowThing.setFid(fid);
            borrowThing.setNum(nums[i]);
            borrowThing.setAcnum(nums[i]);
            borrowThing.setBadnum(0);
            borrowThing.setState(state);
            list.add(borrowThing);
        }
        result=borrowThingMapper.addBorrowThing(list);
        //如果审批通过了还要减去相应的数量
        if(state.equals("审批通过"))
        {
             result=updateThingANdSizeNum(map,fid);
        }
        return result;
    }
    @Override
    public int updateThingANdSizeNum( Map<Integer,Integer> map,Integer fid) {
        int result=0;
        //更新thing的数量
        for (Map.Entry entry : map.entrySet())
        {
            result=thingMapper.updateNumBySymbol((Integer) entry.getKey(),(Integer) entry.getValue(),0);
        }
        //更新size的数量
        List<BorrowThing>borrowThingList=borrowThingMapper.findByFid(fid);
        for(BorrowThing borrowThing:borrowThingList) {
            result=thingSizeMapper.updateNumBySymbol(borrowThing.getSid(),borrowThing.getNum(),0);
        }
        return result;
    }

    @Override
    public Boolean judgeAllThingSize(Integer fId)
    {
        if(fId==null) return false;
        List<BorrowThing>borrowThingList=borrowThingMapper.findByFid(fId);
        for(BorrowThing borrowThing:borrowThingList)
        {
            if(borrowThing.getNum()>thingSizeMapper.findRenumById(borrowThing.getSid()))
            {
                return false;
            }
        }
        return true;
    }

    @Override
    public List<BorrowThing> findBorrowThingByFid(Integer fId)
    {
        if(fId==null)
        return null;
        return borrowThingMapper.findByFid(fId);
    }

    @Override
    public Integer findBySid(Integer sid) {
        return borrowThingMapper.findBySid(sid);
    }

    @Override
    public int deleteBySid(Integer sid)
    {
        return borrowThingMapper.deleteBySid(sid);
    }

    @Override
    public int deleteByTid(Integer tid) {
        return borrowThingMapper.deleteByTid(tid);
    }

    @Override
    public void export(BorrowThingInfoDTO borrowThingInfoDTO, HttpServletResponse response)
    {  User user=(User)SecurityUtils.getSubject().getPrincipal();
        Map<String,String>map=borrowThingInfoDTO.getMapToWord();
        //生成文件
        String outputUrl="/home/jar/"+map.get("applicant")+"记录.docx";
        String inputUrl="/home/jar/model.docx";
//        String outputUrl="src\\main\\resources\\static\\word\\"+map.get("applicant")+"的记录.docx";
//        String inputUrl="src\\main\\resources\\static\\word\\model.docx";
        WordTemplate template=null;
        File file = new File(inputUrl);
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            template = new WordTemplate(fileInputStream);
        } catch(IOException exception){
            exception.printStackTrace();
        }
        if (template!=null)
        template.replaceTag(map);

        File file1 = new File(outputUrl);
        if(file1.exists()==false)
        {
            try {
                file1.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileOutputStream outfile;
        try {
            outfile = new FileOutputStream(file1);
            BufferedOutputStream bos = new BufferedOutputStream(outfile);
            template.write(bos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ServletOutputStream out = null;
        FileInputStream ips = null;

        File result=new File(outputUrl);
        try {
            ips = new FileInputStream(result);
            response.setContentType("application/msword");
            //为下载文件设置名字
            //解决前端 乱码问题
            response.addHeader("Content-Disposition", "attachment;  filename=\"" + new String(result.getName().getBytes("UTF-8"),"ISO8859-1") + "\"");
            //获取响应的输出流
            out = response.getOutputStream();
            //读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = ips.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null && ips != null) {
                    out.close();
                    ips.close();
                }
            } catch (IOException e) {
                System.out.println("关闭流出现异常");
                e.printStackTrace();
            }

        }
        result.delete();
        //return "导出成功";
    }
    @Override
    public int updateInfo(Integer id, Integer acnum, Integer badnum,String state)
    {
        if (id != null && acnum != null && badnum != null)
        {
            //找到那个记录
            BorrowThing borrowThing=borrowThingMapper.findById(id);
           // System.out.println("updateInfo:"+borrowThing);
            //修改改各个物品的数量
           // System.out.println(id+" "+acnum+" "+badnum+" ");
            thingSizeMapper.updateNumBySymbol(borrowThing.getSid(),acnum,null);
            thingMapper.updateNumBySymbol(borrowThing.getTid(),acnum,null);
            if(borrowThing.getBadnum()==0)
            return borrowThingMapper.updateInfo(id, acnum, badnum,  state);
            else return borrowThingMapper.updateInfo(id, borrowThing.getAcnum()+acnum, badnum,  state);
        }

        return 0;
    }

    @Override
    public int updateState(Integer id, String state) {
        if (id != null && state != null)
            return borrowThingMapper.updateState(id, state);
        return 0;
    }

    @Override
    public int updateStateByFid(Integer fId, String state)
    {
        if(fId!=null&&state!=null)
            return borrowThingMapper.updateStateByFid(fId,state);
        return 0;
    }

    @Override
    public BorrowThingInfoDTO findByState(Integer fId,String state)
    {

        BorrowThingDTO borrowThingDTO=new BorrowThingDTO();
        BorrowThingInfoDTO borrowThingInfoDTO=new BorrowThingInfoDTO();
        if (state != null) {
            borrowThingDTO.setBorrowThingDTO(flagMapper.findById(fId),returnTableData(borrowThingMapper.findByState(fId,state)));
            borrowThingInfoDTO.setBorrowThingInfoDTO(borrowThingDTO,null);
            return borrowThingInfoDTO;
        }
        return null;
    }

    @Override
    public Integer findByBadBum(Integer fId)
    {
//        BorrowThingDTO borrowThingDTO=new BorrowThingDTO();
//        if(fId!=null)
//        {
//            borrowThingDTO.setBorrowThingDTO(flagMapper.findById(fId),returnTableData(borrowThingMapper.findByFid(fId)));
//            return borrowThingDTO;
//        }
//        return null;
        if(fId!=null)
            return borrowThingMapper.findByBadBum(fId);
        return 0;
    }

    @Override
    public BorrowThingInfoDTO findByFid(Integer fId)
    {
        if(fId==null) return null;
        BorrowThingDTO borrowThingDTO=new BorrowThingDTO();
        borrowThingDTO.setBorrowThingDTO(flagMapper.findById(fId),returnTableData(borrowThingMapper.findByFid(fId)));
        GetAndReturn getAndReturn=getAndReturnMapper.findByFid(fId);
        BorrowThingInfoDTO borrowThingInfoDTO=new BorrowThingInfoDTO();
        borrowThingInfoDTO.setBorrowThingInfoDTO(borrowThingDTO,getAndReturn);
        DelayThing delayThing=delayThingMapper.findByFid(fId);
        borrowThingInfoDTO.setDelayThing(delayThing);
        return borrowThingInfoDTO;
    }

    @Override
    public BorrowThing findById(Integer id)
    {
        if(id!=null)
            return borrowThingMapper.findById(id);
        return null;
    }


    public List<TableDTO> returnTableData( List<BorrowThing>borrowThingList)
    {
        if(borrowThingList==null) return  null;
        List<TableDTO>tableDTOList=new ArrayList<>();
         for(BorrowThing borrowThing:borrowThingList){
            TableDTO tableDTO=new TableDTO();
            Thing thing=thingMapper.findById(borrowThing.getTid());
            ThingSize thingSize=thingSizeMapper.findById(borrowThing.getSid());
            tableDTO.setTableDTO(thing,thingSize,borrowThing);
            tableDTOList.add(tableDTO);
        }
        return tableDTOList;
    }
}